import sys


def get_hyp(hyp_path):
    hyp = {}
    with open(hyp_path, 'r') as fin:
        for line in fin:
            content = line.split("(")[0].split( )
            utt = line.split("(")[1].split(")")[0]
            hyp[utt] = content
    return hyp


def hpy2ctm(hyp, output=None):
    fout = None
    if output:
        fout = open(output, "w")
    for utt in hyp:
        if len(hyp[utt]) == 0:
            print("{utt} 1 {start} {end} {char}".format(utt=utt, start="{:.2f}".format(0),
                                                        end="{:.2f}".format(1), char="<space>"), file=fout)
        for i, c in enumerate(hyp[utt]):
            print("{utt} 1 {start} {end} {char}".format(utt=utt, start="{:.2f}".format(i),
                                                        end="{:.2f}".format(i + 1), char=c), file=fout)

    if output:
        fout.close()


def main(hyp_path, output):
    hyp = get_hyp(hyp_path)
    hpy2ctm(hyp, output)


if __name__ == "__main__":

    if len(sys.argv) != 3:
        exit(-1)
    hyp_path = sys.argv[
        1]  # "/data/cfs/asr_work/meichaoyang001/aisearch_gpu_home_new/.tmp/jianwei_athena/examples/asr/misp/result/noise_conformer1214_avg20_attention_rescoring_ctc0_7_avg5_tlm0_5_beam20.result"
    output = sys.argv[
        2]  # "/data/cfs/asr_work/meichaoyang001/aisearch_gpu_home_new/.tmp/jianwei_athena/examples/asr/misp/result/noise_conformer1214_avg20_attention_rescoring_ctc0_7_avg5_tlm0_5_beam20.result"

    main(hyp_path, output)

